package com.yyg.usecase.datastructure;


import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

public class LRUCache<K, V>{
    int capacity;
    Map<K, V> keyValueMap;

    Queue<K> queue;


    LRUCache(int capacity) {
        this.capacity = capacity;
        this.keyValueMap = new HashMap<>(capacity);
        this.queue = new LinkedList<>();
    }

    public V get(K key){
        if(keyValueMap.containsKey(key)) {
            queue.remove(key);
            queue.offer(key);
            return keyValueMap.get(key);
        }
        return null;
    }

    public void put(K key, V value){
        if(keyValueMap.containsKey(key)) {
            keyValueMap.put(key, value);
            queue.remove(key);
            queue.offer(key);
        }else {
            int size = keyValueMap.size();
            if(size >= capacity) {
                K lastKey = queue.poll();
                keyValueMap.remove(lastKey);
            }
            keyValueMap.put(key, value);
            queue.offer(key);
        }
    }

    public void display() {
        for (K key : queue) {
            System.out.print(key + "=" + keyValueMap.get(key) + " ");
        }
        System.out.println();
    }
}